#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json

class Settings:
    """设置管理类"""
    
    def __init__(self):
        self.config_file = os.path.join(
            os.path.dirname(os.path.dirname(__file__)), 
            "config", 
            "settings.json"
        )
        
        # 默认设置
        self.settings = {
            "default_username": "",
            "default_email": "",
            "max_concurrent_backups": 3,
            "backup_timeout_minutes": 60,
            "window_geometry": "1000x700",
            "check_for_updates": True,
            "auto_save_interval": 5,
            "log_level": "INFO"
        }
    
    def load(self):
        """加载设置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    loaded_settings = json.load(f)
                    # 合并设置
                    self.settings.update(loaded_settings)
            return True
        except Exception as e:
            print(f"加载设置失败: {e}")
            return False
    
    def save(self):
        """保存设置"""
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.settings, f, indent=4, ensure_ascii=False)
            return True
        except Exception as e:
            print(f"保存设置失败: {e}")
            return False
    
    def get(self, key, default=None):
        """获取设置值"""
        return self.settings.get(key, default)
    
    def set(self, key, value):
        """设置值"""
        self.settings[key] = value
        self.save()
    
    def reset(self):
        """重置设置"""
        self.settings = {
            "default_username": "",
            "default_email": "",
            "max_concurrent_backups": 3,
            "backup_timeout_minutes": 60,
            "window_geometry": "1000x700",
            "check_for_updates": True,
            "auto_save_interval": 5,
            "log_level": "INFO"
        }
        self.save()